import subprocess
import time


import config

# 常量配置
from elm.utils import findCoordinates
from elm.utils import ScreenOperation


def sleep():
    time.sleep(2)


def sleepSetTime(t):
    time.sleep(t)


# 进入elmApp首页
def intoElmApp():
    ScreenOperation.wakeUp()
    ScreenOperation.home()
    page = config.ELM_APP_LOCATION_PAGE
    count = 0
    sleepSetTime(0.5)
    while count < page:
        ScreenOperation.doTurnThePageRight()
        count += 1
        sleep()
    elmIconLocation = findCoordinates.finElmIconLocation()
    if elmIconLocation is None:
        print("找不到饿了么app，请检查页码或图标是否正确！")
        return
    ScreenOperation.doClick(elmIconLocation[0], elmIconLocation[1])
    print("等待广告结束。。。")
    sleepSetTime(7)
    openActivePage()


# 打开活动页面
def openActivePage():
    activePageBtnLocation = findCoordinates.findActivePageBtnLocation()
    if activePageBtnLocation is None:
        print("找不到活动入口，请检查页码或图标是否正确！")
        ScreenOperation.doClick(config.orchard_entrance.get('x'), config.orchard_entrance.get('y'))
    else:
        ScreenOperation.doClick(activePageBtnLocation[0], activePageBtnLocation[1])
    sleepSetTime(5)
    print("等待加载果园")
    # 检查是否有可领取的水滴
    hasNotReceive()


def hasNotReceive():
    finReceiveBtn = findCoordinates.finReceiveBtnLocation()
    if finReceiveBtn is None:
        print("暂无可领取的任务水滴！")
    else:
        ScreenOperation.doClick(finReceiveBtn[0], finReceiveBtn[1])
        num = 0
        while num < 3:
            receiveBtn = findCoordinates.findCanReceiveBtnLocation()
            if receiveBtn is None:
                print("暂无可领取水滴！")
            else:
                print(receiveBtn)
                ScreenOperation.doClick(receiveBtn[0], receiveBtn[1])
            sleepSetTime(3)
            ScreenOperation.doTurnThePageDown()
            num += 1
        closeReceivePageBtnLocation = findCoordinates.findCloseReceivePageBtnLocation()
        if closeReceivePageBtnLocation is None:
            print("找不到领取水滴页面关闭按钮！")
            return
        else:
            ScreenOperation.doClick(closeReceivePageBtnLocation[0], closeReceivePageBtnLocation[1])
    ScreenOperation.doClick(config.activity_location.get('x'), config.activity_location.get('y'))
    happyAcceptBtnLocation = findCoordinates.findHappyAcceptBtnLocation()
    sleepSetTime(1)
    if happyAcceptBtnLocation is None:
        print("暂无可领取水滴！")
    else:
        ScreenOperation.doClick(happyAcceptBtnLocation[0], happyAcceptBtnLocation[1])

if __name__ == '__main__':
    intoElmApp()